﻿
#include "AMWebEnginePage.h"

AMUrlRequestInterceptor::AMUrlRequestInterceptor(QObject* p /*= nullptr*/)
    : QWebEngineUrlRequestInterceptor(p)
{
}

AMUrlRequestInterceptor::~AMUrlRequestInterceptor()
{
}

void AMUrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo& info)
{
    //修改请求头
    //info.setHttpHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36");
}

AMWebEnginePage::AMWebEnginePage(QObject* parent)
    : QWebEnginePage(parent)
{
    auto* interceptor = new AMUrlRequestInterceptor(this);
    this->setUrlRequestInterceptor(interceptor);

    QWebEngineProfile* profile = this->profile();
    //profile->setUrlRequestInterceptor(interceptor);
    connect(profile, &QWebEngineProfile::downloadRequested, this, &AMWebEnginePage::sltDownloadRequested);

    QWebEngineCookieStore* cookieStore = profile->cookieStore();
    connect(cookieStore, &QWebEngineCookieStore::cookieAdded, this, &AMWebEnginePage::sltCookieAdded);

    QNetworkCookie cookie("abc", "123456");
    cookieStore->setCookie(cookie, QUrl("http://baidu.com"));
}

AMWebEnginePage::~AMWebEnginePage()
{
}

void AMWebEnginePage::sltDownloadRequested(QWebEngineDownloadItem* download)
{
    //接受文件下载请求
    download->accept();
    //finished()信号，仅在DownloadCompleted状态时发送，无法获取到下载失败的信号,所以使用stateChanged()信号
    connect(download, &QWebEngineDownloadItem::stateChanged, this, &AMWebEnginePage::sltDownloadStateChanged);
}

void AMWebEnginePage::sltDownloadStateChanged()
{
    QWebEngineDownloadItem* download = dynamic_cast<QWebEngineDownloadItem*>(sender());
    if (download->state() >= QWebEngineDownloadItem::DownloadCompleted)
    {
        emit sgnDownloadFileFinished(download);
    }
}

QStringList AMWebEnginePage::chooseFiles(FileSelectionMode mode, const QStringList& oldFiles, const QStringList& acceptedMimeTypes)
{
    QStringList strLst = QWebEnginePage::chooseFiles(mode, oldFiles, acceptedMimeTypes);
    return strLst;
}

bool AMWebEnginePage::certificateError(const QWebEngineCertificateError& certificateError)
{
    qDebug() << certificateError.errorDescription();
    //忽略证书错误
    return true;
}


void AMWebEnginePage::sltCookieAdded(const QNetworkCookie& cookie)
{
    qDebug() << cookie;
}
